//
//  LZSOneVC.m
//  IOSProject
//
//  Created by lzs on 2018/4/18.
//  Copyright © 2018年 com.linzhisheng. All rights reserved.
//

#import "LZSOneVC.h"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import "LZSOneCell.h"
#import "LZSTouTiaoModel.h"

//
#import "LZSArticelDetailViewController.h"

#import "LZSFMDBManager.h"

#import "SXTLoginViewController.h"

@interface LZSOneVC ()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger start;
@property (nonatomic, strong) NSMutableArray *realArray;
@end

@implementation LZSOneVC

-(NSMutableArray *)realArray{
    if (!_realArray) {
        _realArray = [NSMutableArray array];
    }
    return _realArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorColor = [UIColor lightGrayColor];
    //
    self.tableView.estimatedRowHeight = 80;
    
    self.tableView.separatorColor = [UIColor colorWithHexString:@"#c8c8c8"];
    
    //默认【下拉刷新】
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    //默认【上拉加载】
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    //
    self.tableView.tableFooterView = [UIView new];
    
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).mas_offset(-64-49);
    }];
    
    [self headerSdcycleScrollView];
    
    //
    [self.tableView.mj_header beginRefreshing];
}

-(void)toutiao{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"31771dfbcb6cda3d" forKey:@"appkey"];
    [params setValue:@"头条" forKey:@"channel"];
    [params setValue:@"40" forKey:@"num"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)self.start] forKey:@"start"];
    
    [self getData:@"http://api.jisuapi.com/news/get" param:params success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        NSLog(@"%@",responseObject);
        LZSTouTiaoModel *datamodel = [LZSTouTiaoModel mj_objectWithKeyValues:responseObject[@"result"]];
        
        //是刷新还是加载
        if (self.start==0) {
            if (datamodel.list.count==0) {
                //                self.noDataView.hidden = NO;
                self.tableView.hidden = YES;
            }else{
                //                self.noDataView.hidden = YES;
                self.tableView.hidden = NO;
            }
            
            [self.realArray removeAllObjects];
            [self.realArray addObjectsFromArray:datamodel.list];
        }else{
            [self.realArray addObjectsFromArray:datamodel.list];
        }
        
        //是否提示可加载
        if (datamodel.list.count<10) {
            // 变为没有更多数据的状态
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            self.tableView.mj_footer.hidden = YES;
        }else{
            self.start++;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"%@",error);
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

    }];
}

-(void)refresh{
    self.start = 0;
    [self toutiao];
    
}

-(void)loadMore{
//    sleep(2);
//    [self toutiao];
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.realArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LZSOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[LZSOneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell.btn setTag:indexPath.row];
    [cell.btn addTarget:self action:@selector(collectionBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.Listmodel = self.realArray[indexPath.row];
    return cell;
}

-(void)collectionBtn:(UIButton *)btn{
    
    NSDictionary *loginDic = [[NSUserDefaults standardUserDefaults]valueForKey:@"ISLOGIN"];
    if (loginDic.count) {
        //将数据写入数据库里面
        LZSListModel *model = self.realArray[btn.tag];
        NSDictionary *listDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                 model.title,@"title",model.time,@"time",model.src,@"src",model.category,@"category",model.pic,@"pic",model.content,@"content",model.url,@"url",model.weburl,@"weburl",nil];
        //    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:responseObject[@"data"]];
        //    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
        //    NSData *dicData = [NSJSONSerialization dataWithJSONObject:model options:NSJSONWritingPrettyPrinted error:nil];
        NSData *dicData = [NSJSONSerialization dataWithJSONObject:listDic options:NSJSONWritingPrettyPrinted error:nil];
        NSLog(@"====");
        //增加一条
        [[LZSFMDBManager fmdbManager] addDataWithTableName:loginDic[@"name"] primaryKey:model.url data:dicData];
        [self.view makeToast:@"收藏成功" duration:0.8 position:CSToastPositionCenter];
    }else{
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"亲,您还未登录,暂时无法使用该功能~" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okaction = [UIAlertAction actionWithTitle:@"去登陆" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            SXTLoginViewController *loginVc = [[SXTLoginViewController alloc] init];
            [self.navigationController pushViewController:loginVc animated:YES];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertVC addAction:okaction];
        [alertVC addAction:cancelAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

-(void)headerSdcycleScrollView{
    SDCycleScrollView *cycview = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120) delegate:self placeholderImage:[UIImage imageNamed:@"购物车界面客服热线图标.png"]];
    cycview.localizationImageNamesGroup = @[@"cp1.png",@"cp2.png",@"cp3.png"];
    cycview.autoScrollTimeInterval = 2;
    cycview.autoScroll = YES;
    cycview.infiniteLoop = YES;
    self.tableView.tableHeaderView = cycview;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LZSListModel *model = self.realArray[indexPath.row];
    LZSArticelDetailViewController *articlevc = [[LZSArticelDetailViewController alloc] init];
                           articlevc.titlestr = model.title;
                           articlevc.timestr = model.time;
                           articlevc.srcStr = model.src;
                           articlevc.content = model.content;
    [self.navigationController pushViewController:articlevc animated:YES];
}

/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    NSLog( @"%ld",(long)index);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
